import os
from chilin2.helpers import JinjaTemplateCommand, template_dump

def qc_read_coverage(input={"treat":"","control":"","DHS_sites":"", "latex_template": ""},
                     output = {"rfile": "", "latex": "", "pdf": "", "DHS_sites_treat": ""},
                     param = {}):

    r_content = '''
x = treat[,6]/treat[,2]
y = control[,6]/control[,2]

percent_calculate = function(x){
x1 = x/sum(x)
x2 = sort(x1)
ll = length(x)
bin_length = trunc(ll/1000,0)
bin_matrix=matrix(x2[1:(bin_length*1000)],ncol=1000)
bin=colSums(bin_matrix)
result = c()
result[1]=bin[1]
for (i in seq(2,1000)){
result[i] = result[i-1]+bin[i]
}

return(result)
}

treat_result = percent_calculate(x)
control_result = percent_calculate(y)

pdf('%s')
plot(control_result,type='l',xlab='percent of bin',ylab = 'percent of DHS site read coverage',xaxt='n' )
points(treat_result,type='l',col='red')
axis(1, at=seq(0,1000,200),labels=seq(0,1,0.2))
legend('topleft',c('input','treat'),lty=c(1,1),col=c('black','red'))
dev.off()
    '''%output["pdf"]
    print(input["treat"])
    print(input["control"])
    with open(output["rfile"],'w') as f:
        rline = "treat = read.table('%s',header=F)\n" % input["treat"]
        f.write(rline)
        rline = "control = read.table('%s',header=F)\n" % input["control"]
        f.write(rline)
        f.write(r_content)

    # change execute pattern
    os.system('Rscript %s'%output['rfile'])

    read_enrichment_latex = JinjaTemplateCommand(
        name="read enrichment",
        template=input["latex_template"],
        param={"section_name": "read_enrichment",
               "read_enrichment_graph": output["pdf"],
               "render_dump": output["latex"]})

    template_dump(read_enrichment_latex)